import { Component, OnInit } from '@angular/core';
import { ModalController, NavController, PopoverController } from '@ionic/angular';
import { Router } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';
import { HttpService } from 'src/app/service/http.service';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { FilterListComponent } from '../../../components/filter-list/filter-list.component';
import { Device } from '@ionic-native/device/ngx';
import { RegionPickModelComponent } from '../../../components/region-pick-model/region-pick-model.component';
import { RadioPickModelComponent } from '../../../components/radio-pick-model/radio-pick-model.component';
import { CalendarModelComponent } from '../../../components/calendar-model/calendar-model.component';
import { AppointHomeModelComponent } from '../../../components/appoint-home-model/appoint-home-model.component';
import {ThemeableBrowser, ThemeableBrowserOptions} from '@ionic-native/themeable-browser/ngx';

@Component({
    selector: 'app-patient-home',
    templateUrl: './patient-home.page.html',
    styleUrls: ['./patient-home.page.scss'],
})
export class PatientHomePage implements OnInit {
    doctorList = [];
    stopLoad = false;
    checkedList: Array<any> = [];
    departmentId = '';
    hospitalId = '';
    regionId = '';
    userData: any = {};
    queryParams: any = {};
    queryOffset = 0;
    queryLimit = 10;
    menuHeaderStyle = {};
    enterTimes = 0;
    unreadNum = 0;
    isIos = 0; // 0不是ios 1是ios
    launcherType = 1;
    cityAreaList = [];
    sysLang = '';

    segmentTabs: Array<any> = [
        {
            label: 'Region',
            value: 'region'
        },
        {
            label: 'Department',
            value: 'department'
        },
        {
            label: 'Date',
            value: 'appoint'
        },
    ];

    constructor(
        private device: Device,
        private router: Router,
        private statusBar: StatusBar,
        private navController: NavController,
        private httpService: HttpService,
        private translate: TranslateService,
        private modalController: ModalController,
        private popoverController: PopoverController,
        private themeableBrowser: ThemeableBrowser,
    ) {

    }

    async ngOnInit() {
        this.sysLang = this.translate.getBrowserCultureLang().toLowerCase();
        await this.getLauncherType();
        await this.queryDoctorList(true);
        this.statusBar.backgroundColorByHexString('#009e41');
        if (this.device.platform) {
            if (this.device.platform.toUpperCase() === 'ANDROID') {
                this.menuHeaderStyle = {'margin-top': '44px'};
                this.isIos = 0;
            } else if (this.device.platform.toUpperCase() === 'IOS') {
                this.menuHeaderStyle = {'margin-top': '44px'};
                this.isIos = 1;
            }
        }

        // await this.getCityAreaList();
        // await this.showAppointmentModel();
    }

    private async getCityAreaList() {
        const result = await this.httpService.get()
            .setPath('/pub/source/cityAreaList')
            .request();

        if (result.status === 0) {
            this.cityAreaList = result.data;
        }
    }

    private async showAppointmentModel() {
        const modal = await this.modalController.create({
            component: AppointHomeModelComponent,
            componentProps: {
                cityAreaList: this.cityAreaList
            }
        });
        await modal.present();
        const { data } = await modal.onDidDismiss();
        if (data) {
            this.queryParams = {
                ...this.queryParams,
                ...data
            };
            await this.queryDoctorList(true);
        }
    }

    public async onSegmentClick(value) {
        switch (value) {
            case 'region':
                await this.showRegionModal();
                break;

            case 'department':
                await this.showDepartmentModel();
                break;

            case 'appoint':
                await this.showCalendarModel();
                break;
        }

        await this.queryDoctorList(true);
    }

    public async showCalendarModel() {
        const modal = await this.modalController.create({
            component: CalendarModelComponent,
            componentProps: {
                title: 'SelectDate',
            }
        });
        await modal.present();
        const { data } = await modal.onDidDismiss();
        if (!!data) {
            this.queryParams.queryDate = data;
        }
    }

    public async getPersonInfo() {
        const aUserId = localStorage.getItem('userId');
        const result: any = await this.httpService.get()
            .setPath('/user/patientInfo/' + aUserId)
            .request();
        if (result.status === 0) {
            this.userData = result.data;
            const { nickname, gender, birthday, medical_history, medical_desc, english_name } = this.userData;
            localStorage.setItem('englishName', english_name);
            if (!nickname || !gender || !birthday || !medical_history || !medical_desc || !english_name) {
                if (this.enterTimes === 1) {
                    await this.navController.navigateForward('/patient-personal-center');
                }
            }
        }
    }

    async ionViewDidEnter() {
        this.enterTimes += 1;
        await this.getPersonInfo();

        if (this.launcherType === 1) {
            await this.getUnreadList();
        } else if (this.launcherType === 2) {
            await this.queryPatientAppointOrder();
        }
    }

    public async toPage() {
        await this.navController.navigateForward(['patient-password'], {
            queryParams: { isForgetPassword: '1' }
        });
    }

    public async signOut() {
        await this.httpService.put()
            .setPath('/user/userLogout')
            .request();

        localStorage.removeItem('userId');
        localStorage.removeItem('userType');
        localStorage.removeItem('auth-token');
        localStorage.removeItem('redirectTo');
        await this.navController.navigateRoot('/login');
    }

    public async logOut() {
        await this.httpService.put()
            .setPath('/user/userLogoff')
            .request();

        localStorage.removeItem('userId');
        localStorage.removeItem('userType');
        localStorage.removeItem('auth-token');
        localStorage.removeItem('redirectTo');
        await this.navController.navigateRoot('/login');
    }

    public onHelp() {
        let helpTitle = '使用帮助';
        if (this.sysLang === 'en-us') {
            helpTitle = 'Guide';
        }

        const helpLink = 'http://www.sincaremedicaltour.com/news_detail.php?id=438';
        const options: ThemeableBrowserOptions = {
            statusbar: {
                color: '#009e41'
            },
            toolbar: {
                height: 44,
                color: '#009e41'
            },
            title: {
                color: '#ffffff',
                staticText: helpTitle,
                showPageTitle: true
            },
            backButton: {
                wwwImage: '/assets/icon/direction-left.png',
                wwwImagePressed: '/assets/icon/direction-left.png',
                imagePressed: 'back_pressed',
                align: 'left',
                event: 'backPressed'
            },
            backButtonCanClose: true
        };

        this.themeableBrowser.create(helpLink, '_blank', options);
    }

    private async getLauncherType() {
        const result = await this.httpService.get()
            .setPath('/pub/user/getLauncherType')
            .request();

        if (result.status === 0) {
            this.launcherType = Number(result.data.launcherType);
            if (this.launcherType === 2) {
                this.segmentTabs = this.segmentTabs.filter(item => item.value !== 'department');
            }
        }
    }

    public async queryDoctorList(refresh: boolean) {
        if (refresh) {
            this.queryOffset = 0;
        }

        const requestMethod = {
            1: '/pub//user/doctorList',
            2: '/pub/user/hospitalUserList'
        };

        if (!this.queryParams.queryDate) {
            // this.queryParams.queryDate = this.httpService.getDatetimeString();
            this.queryParams.queryDate = this.httpService.getTomorrowDateString();
        }

        const result = await this.httpService.get()
            .setPath(requestMethod[this.launcherType])
            .setQuery({
                ...this.queryParams,
                offset: this.queryOffset,
                limit: this.queryLimit,
                doctorState: 1,
            })
            .request();

        if (result.status === 0) {
            if (refresh) {
                this.doctorList = result.data.rows;
            } else {
                if (this.doctorList.length < result.data.count) {
                    this.doctorList = [
                        ...this.doctorList,
                        ...result.data.rows
                    ];
                }
            }
            this.queryOffset = this.doctorList.length;
            this.stopLoad = this.doctorList.length === result.data.count;
        }
    }

    public async onDoctorSelect(doctor) {
        if (this.launcherType === 2) {
            if (doctor.order_type === 1) {
                if (doctor.has_order) {
                    const userId = localStorage.getItem('userId');
                    await this.navController.navigateForward(['hospital-info'], {
                        queryParams: {
                            hospitalUserId: doctor.id,
                            patientUserId: userId,
                            hasOrder: doctor.has_order
                        }
                    });
                } else {
                    this.onHelp();
                }
            } else if (doctor.order_type === 2) {
                this.onHelp();
            }
        } else {
            await this.navController.navigateForward(['patient-doctorinfo'], {
                queryParams: {
                    doctorId: doctor.id,
                    hasOrder: doctor.has_order
                }
            });
        }
    }

    public async showFilter() {
        const popover = await this.popoverController.create({
            component: FilterListComponent,
            cssClass: 'custom-popover',
            componentProps: {
                checkedList: this.checkedList
            }
        });
        await popover.present();
        const popoverResult = await popover.onDidDismiss();
        if (popoverResult.data) {
            const { checkedList, checkedResult } = popoverResult.data;
            this.checkedList = checkedList;
            this.queryParams = checkedResult;
            await this.queryDoctorList(true);
        }
    }

    public async doRefresh(event) {
        await this.queryDoctorList(true);
        event.target.complete();
    }

    public async loadData(event) {
        await this.queryDoctorList(false);
        event.target.complete();
    }

    private async showRegionModal() {
        const result: any = await this.httpService.get()
            .setPath('/pub/source/threeRegionData')
            .setQuery({
                style: 'tree',
                appointNation: this.launcherType === 2 ? 'us' : null,
                isCityArea: this.launcherType === 2 ? 1 : null
            })
            .request();

        if (result.status === 0) {
            const modal = await this.modalController.create({
                component: RegionPickModelComponent,
                componentProps: {
                    title: 'District Choose',
                    fixedNation: this.launcherType === 2 ? 'us' : null,
                    itemArray: [
                        {
                            name: 'Country Choose',
                            type: 1,
                        },
                        {
                            name: 'State Choose',
                            type: 2,
                        },
                        {
                            name: 'City Choose',
                            type: 3
                        },
                    ],
                    dataArray: [ ...result.data ]
                }
            });
            await modal.present();
            const { data } = await modal.onDidDismiss();
            if (data) {
                const [ , , region ] = data;
                delete this.queryParams.cityAreaId;
                this.queryParams.regionId = region.value;
            }
        }
    }

    private async showDepartmentModel() {
        const result: any = await this.httpService.get()
            .setPath('/pub/source/departmentList')
            .request();

        if (result.status === 0) {
            const modal = await this.modalController.create({
                component: RadioPickModelComponent,
                componentProps: {
                    title: '选择部门',
                    labelProp: 'name',
                    dataList: [ ...result.data ],
                    selectValue: this.queryParams.departmentId
                }
            });
            await modal.present();
            const { data } = await modal.onDidDismiss();
            if (data) {
                this.queryParams.departmentId = data.value;
            }
        }
    }

    private async showOrderTypeModel() {
        const modal = await this.modalController.create({
            component: RadioPickModelComponent,
            componentProps: {
                title: '选择预约方式',
                dataList: [
                    {
                        label: '直接预约',
                        value: 1
                    },
                    {
                        label: '代理预约',
                        value: 2
                    }
                ],
                selectValue: this.queryParams.orderType
            }
        });
        await modal.present();
        const { data } = await modal.onDidDismiss();
        if (data) {
            this.queryParams.orderType = data.value;
        }
    }

    async onFilterReset() {
        this.queryParams = {};
        await this.queryDoctorList(true);
    }

    public async getUnreadList() {
        const aUserId = localStorage.getItem('userId');
        const result: any = await this.httpService.get()
            .setPath('/order/unreadCount')
            .setQuery({
                userId: aUserId
            })
            .request();
        if (result.status === 0) {
            this.unreadNum = result.data[0].count;
        }
    }

    private async queryPatientAppointOrder() {
        const aUserId = localStorage.getItem('userId');
        const result: any = await this.httpService.get()
            .setPath('/order/orderInfo')
            .setQuery({
                patientUserId: aUserId,
                orderType: 1,
                bookingType: 2,
                acceptType: 2
            })
            .request();
        if (result.status === 0) {
            this.unreadNum = result.data ? 1 : 0;
        }
    }

    public toPrivacy() {
        this.navController.navigateForward(['privacy']);
    }
}
